package com.netmi.mykotlinlearning.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.animation.Animation;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import static java.lang.System.out;

/**
 * 类描述：用于android 10.0及其以上 保存图片到本地
 * 创建人：tgw
 * 创建时间：2020/8/7
 * 修改备注：
 */
public class SaveImageUtils {

    public boolean saveBitmap2Gallery2(Context context, Bitmap bitmap) {
        String name = System.currentTimeMillis() + "";
        String photoPath = Environment.DIRECTORY_DCIM + "/Camera";
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, photoPath);//保存路径
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, true);
        }

        Uri insert = context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues);

        if (insert == null){
            //插入失败
            return false;
        }

        try {
            OutputStream outputStream = context.getContentResolver().openOutputStream(insert);
            if (outputStream == null){
                return false;
            }

            if(bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)){
                outputStream.flush();
                outputStream.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            contentValues.put(MediaStore.MediaColumns.IS_PENDING, false);
        }
        return true;

    }


}

